package partner

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

//添加钻石记录
func NewCardRecord(cr map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessPartner)
	values, sql := InsertSql(TablePfCardRecord, cr)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//代理钻石买卖的记录
func ListCardRecord(p ListCardParams, agentId int64, multiOrm ...orm.Ormer) ([]*PfCardRecord, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf(" agent_id = %v ", agentId)
	if p.PlayerId != 0 {
		where = where + fmt.Sprintf(" AND player_id = %v ", p.PlayerId)
	}
	if p.Type != 0 {
		where = where + fmt.Sprintf(" AND type = %v ", p.Type)
	}
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			%v
		ORDER BY id DESC
		LIMIT ?,?
		`, TablePfCardRecord, where)
	o := NewOrm(multiOrm, DBChessPartner)
	var cr []*PfCardRecord
	_, err := o.Raw(sql, limit, p.PageSize).QueryRows(&cr)
	if CheckError(err) {
		return cr, 0, err
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v WHERE %v`, TablePfCardRecord, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return cr, 0, err
	}
	return cr, count, nil
}

//统计当前代理累计买，累计卖了多少张钻石,剩余钻石数
func StatCardInfo(agentId int64, multiOrm ...orm.Ormer) (StatCard, error) {
	sql := fmt.Sprintf(`
		SELECT
			IF(SUM(card_num) is NULL,0,SUM(card_num)) AS buy_card
		FROM
			%v
		WHERE
			agent_id = %d AND type = %v
	`, TablePfCardRecord, agentId, BuyRoomCard)
	o := NewOrm(multiOrm, DBChessPartner)
	var stat StatCard
	err := o.Raw(sql).QueryRow(&stat.BuyCard)
	if CheckError(err) {
		return stat, err
	}

	sql = fmt.Sprintf(`
		SELECT
			IF(SUM(card_num) is NULL,0,SUM(card_num)) AS sell_card
		FROM
			%v
		WHERE
			agent_id = %d AND type = %v
	`, TablePfCardRecord, agentId, HandleTopUp)
	err = o.Raw(sql).QueryRow(&stat.SellCard)
	if CheckError(err) {
		return stat, err
	}

	sql = fmt.Sprintf(`
		SELECT
			rmcard,rmcard_forze
		FROM
			%v
		WHERE
			uid = %v
	`, TableClientUser, agentId)
	o1 := NewDBOrm(DBChess)
	var rmCard, rmCardForze int64
	o1.Raw(sql).QueryRow(&rmCard, &rmCardForze)
	sql = fmt.Sprintf(`
		SELECT
			card_num
		FROM
			%v
		WHERE
			uid = %d
	`, TablePfCardCash, agentId)
	err = o.Raw(sql).QueryRow(&stat.RestCard)
	if CheckError(err) {
		return stat, err
	}
	stat.RestCard = stat.RestCard + rmCardForze + rmCard
	return stat, nil
}

//更新充值过的玩家的信息
func UpdateOrInsertAgentPlayer(ap map[string]interface{}, playerId, agentId int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessPartner)
	ap["player_id"] = playerId
	ap["agent_id"] = agentId
	values, sql := InsertOrUpdateSql(TablePfAgentPlayer, ap)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//在代理充值过或代充过的玩家列表
func ListAgentPlayer(p ListParams, agentId int64, multiOrm ...orm.Ormer) ([]*PfAgentPlayer, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			player_id,remark
		FROM
			%v
		WHERE
			agent_id = %v
		ORDER BY
			create_time DESC
		LIMIT ?,?
		`, TablePfAgentPlayer, agentId)
	o := NewOrm(multiOrm, DBChessPartner)
	var player []*PfAgentPlayer
	_, err := o.Raw(sql, limit, p.PageSize).QueryRows(&player)
	if CheckError(err) {
		return player, 0, err
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v WHERE agent_id = %d`,
		TablePfAgentPlayer, agentId)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return player, 0, err
	}
	return player, count, nil
}

//返回当前代理剩余多少张钻石
func RestCard(agentId int64, multiOrm ...orm.Ormer) (int64, error) {
	sql := fmt.Sprintf(`
		SELECT
			card_num
		FROM
			%v
		WHERE
			uid = %d
	`, TablePfCardCash, agentId)
	o := NewOrm(multiOrm, DBChessPartner)
	var restCard int64
	err := o.Raw(sql).QueryRow(&restCard)
	if CheckError(err) {
		return 0, err
	}
	return restCard, nil
}

//列出钻石列表
func ListCard(typ int64, multiOrm ...orm.Ormer) ([]Card, error) {
	var card []Card
	key := fmt.Sprintf("%v%v", KeyCardList, typ)
	err := GetCache(RedisCache, key, &card)
	if err != nil {
		sql := fmt.Sprintf(`SELECT * FROM %v WHERE type = %v ORDER BY num
		`, TableH5CardPrice, typ)
		o := NewOrm(multiOrm, DBChessSysData)
		_, err := o.Raw(sql).QueryRows(&card)
		if CheckError(err) {
			return card, err
		}
		SetCache(RedisCache, key, card, CacheExpire)
	}
	if typ == AgentGiveCard { //赠送房价没有价格，所以不用下一步了
		return card, nil
	}

	//获取一级，二级代理进货价，玩家直充进货价
	if typ == RulePartnerCardPrice {
		typ = RulePfUnitCardPrice
	}
	r, err := RuleByType(typ)
	if err != nil {
		return nil, err
	}

	for k := range card {
		card[k].Amount = r.Amount * card[k].Num
		card[k].UnitPrice = r.Amount
	}
	return card, nil
}

//查找售卖的钻石
func CardById(id, typ int64, multiOrm ...orm.Ormer) (*Card, error) {
	cardList, err := ListCard(typ, multiOrm...)
	if err != nil {
		return nil, err
	}
	var c Card
	for _, v := range cardList {
		if v.Id == id && v.Type == typ {
			c = v
			return &c, nil
		}
	}
	return nil, nil
}
